package com.ruoyi.system.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.system.domain.Quotation;
import com.ruoyi.system.domain.QuotationItems;
import com.ruoyi.system.mapper.QuotationMapper;
import com.ruoyi.system.mapper.ProductMapper;
import com.ruoyi.system.service.IQuotationService;
import com.ruoyi.system.service.IProgressTemplateService;
import com.ruoyi.system.domain.ProgressTemplateNode;
import com.ruoyi.system.domain.Customer;
import com.ruoyi.system.mapper.CustomerMapper;


@Service
public class QuotationServiceImpl implements IQuotationService {
    @Autowired
    private QuotationMapper quotationMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private IProgressTemplateService progressTemplateService;

    @Autowired
    private CustomerMapper customerMapper;

    /**
     * 查询报价单列表
     */
    @Override
    public List<Quotation> selectQuotationList(Quotation quotation) {
        return quotationMapper.selectQuotationList(quotation);
    }

    /**
     * 查询报价单详细信息
     */
    @Override
    public Map<String, Object> selectQuotationById(Long quotationId) {
        Map<String, Object> result = new HashMap<>();
        // 获取报价单基本信息
        Quotation quotation = quotationMapper.getQuotationById(quotationId);
        // 获取报价单明细
        List<QuotationItems> items = quotationMapper.getQuotationItemsByQuotationId(quotationId);

        result.put("quotation", quotation);
        result.put("items", items);

        return result;
    }

    /**
     * 新增报价单
     */
    @Override
    @Transactional
    public int insertQuotation(Quotation quotation) {
        // 1. 设置基础信息
        quotation.setQuotationDate(new Date());
        quotation.setNumber(generateQuotationNumber());

        // 2. 获取并设置客户信息
        Customer customer = customerMapper.selectCustomerById(quotation.getCustomerId());
        if (customer != null) {
            quotation.setCustomerName(customer.getCustomerName());
            quotation.setContactPerson(customer.getContactPerson());
            quotation.setPhone(customer.getPhone());
        }

        // 3. 设置初始状态为待审批
        quotation.setStatus("待审批");

        // 4. 新增报价单
        int rows = quotationMapper.insertQuotation(quotation);

        // 5. 如果有模板ID，创建进度节点
        if (quotation.getTemplateId() != null) {
            progressTemplateService.createProgressFromTemplate(quotation.getTemplateId(), 
                quotation.getQuotationId(), quotation.getNumber());
        }

        return rows;
    }

    /**
     * 生成报价单编号
     * 生成规则: BJ + 年月日 + 4位流水号
     */
    private String generateQuotationNumber() {
        // 获取当前日期
        String date = DateUtils.dateTimeNow("yyyyMMdd");
        // 查询当天最大编号
        String prefix = "BJ" + date;
        String maxNumber = quotationMapper.getMaxNumberByPrefix(prefix);

        int sequence = 1;
        if (maxNumber != null) {
            // 获取当前序列号并加1
            sequence = Integer.parseInt(maxNumber.substring(10)) + 1;
        }

        // 格式化4位流水号
        return prefix + String.format("%04d", sequence);
    }

    /**
     * 修改报价单
     */
    @Override
    @Transactional
    public int updateQuotation(Quotation quotation) {
        return quotationMapper.updateQuotation(quotation);
    }

    /**
     * 删除报价单
     */
    @Override
    @Transactional
    public int deleteQuotationById(Long quotationId) {
        // 删除明细
        quotationMapper.deleteQuotationItemsByQuotationId(quotationId);
        // 删除主表
        return quotationMapper.deleteQuotationById(quotationId);
    }

    /**
     * 批量删除报价单
     */
    @Override
    @Transactional
    public int deleteQuotationByIds(Long[] quotationIds) {
        for (Long quotationId : quotationIds) {
            // 删除明细
            quotationMapper.deleteQuotationItemsByQuotationId(quotationId);
        }
        // 删除主表
        return quotationMapper.deleteQuotationByIds(quotationIds);
    }

    /**
     * 新增报价单明细
     */
    @Override
    public int insertQuotationItems(QuotationItems item) {
        Product product = productMapper.selectProductById(item.getProductId());
        if (product != null) {
            item.setProductName(product.getProductName());
        }
        return quotationMapper.insertQuotationItems(item);
    }

    /**
     * 批量新增报价单明细
     */
    @Override
    public int batchInsertQuotationItems(List<QuotationItems> items) {
        for (QuotationItems item : items) {
            Product product = productMapper.selectProductById(item.getProductId());
            if (product != null) {
                item.setProductName(product.getProductName());
            }
        }
        return quotationMapper.batchInsertQuotationItems(items);
    }
}
